﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Wholesaler.Models.DBModels;
using Yunzuan.Common.Log;
using Yunzuan.Common.ServiceReference1;
using Yunzuan.Foundation.DataAccess;
using YunZuan.Models.Entities;
using Yunzuan.Foundation.Web;
using Yunzuan.Foundation.Web_api;
using YunZuan.Models;

namespace Yunzuan.Common
{
    public class ConmonMQMsgClass
    {
        #region 发送消息 和查询操作记录

        public delegate void SendMsgDelegate(string name);

        /// <summary>
        /// 异步发送消息
        /// </summary>
        /// <param name="msg"></param>
        public static void send(string msg)
        {
            SendMsgDelegate sendMsg = SendMsgOpLog;
            sendMsg.BeginInvoke(msg, null, null);
        }
        public static void send(Msg msg)
        {
            SendMsgDelegate sendMsg = SendMsgOpLog;
            string strMsg = JsonConvert.SerializeObject(msg);
            sendMsg.BeginInvoke(strMsg, null, null); 
        }  
        public static void SendMsgOpLog(string strParam)
        {
            try
            {
                MessageServiceClient mc = new MessageServiceClient();
                mc.SendMsgOpLog(strParam);
            }
            catch (Exception ex)
            {

                throw;
            }
           
        }

        public static string GetUserLoginLog(string strParam)
        {
            MessageServiceClient mc = new MessageServiceClient();
            return mc.GetUserLoginLog(strParam);
        }
        public static string SearchOperationLog(string strParam)
        {
            MessageServiceClient mc = new MessageServiceClient();
            return mc.SearchOperationLog(strParam);
        }

        public delegate string ReceiveSearchLogDelegate(string strParam);
        public static string GetSearchLog(string msg)
        {
            ReceiveSearchLogDelegate getMsg = SearchList;
            IAsyncResult result = getMsg.BeginInvoke(msg, null, null);
            string res = getMsg.EndInvoke(result);
            return res;
        }

        public delegate string ReceiveSearchLogCountDelegate(string strParam);
        public static string GetSearchLogCount(string msg)
        {
            ReceiveSearchLogCountDelegate getMsg = SearchListCount;
            IAsyncResult result = getMsg.BeginInvoke(msg, null, null);
            string res = getMsg.EndInvoke(result);
            return res;
        }
        /// <summary>
        /// 统计明细
        /// </summary>
        /// <param name="strParam"></param>
        /// <returns></returns>
        public static string SearchDetailByWeight(string strParam)
        {
            MessageServiceClient mc = new MessageServiceClient();
            return mc.SearchDetailByWeight(strParam);
        }
        /// <summary>
        /// 详细信息
        /// </summary>
        /// <param name="strParam"></param>
        /// <returns></returns>
        public static string SearchDetail(string strParam)
        {
            MessageServiceClient mc = new MessageServiceClient();
            return mc.SearchDetail(strParam);
        }
        /// <summary>
        /// 统计
        /// </summary>
        /// <param name="strParam"></param>
        /// <returns></returns>
        public static string SearchList(string strParam)
        {
            MessageServiceClient mc = new MessageServiceClient();
            return mc.SearchList(strParam);
        }
        public static string SearchListCount(string strParam)
        {
            MessageServiceClient mc = new MessageServiceClient();
            return mc.SearchListCount(strParam);
        }

        #endregion
        #region 异步处理供应商
        public delegate void UpdateSupplierDelegate(List<string> list, int SupplierType, string key);

        public static void UpdateSupplierSet(List<string> list, int SupplierType, string key)
        {
            UpdateSupplierDelegate updateSupplier = ReSetSuppliers;
            updateSupplier.Invoke(list, SupplierType, key);
        }
        //重置  SetSuppliers
        // setSupplierJson = "{\"whitelist\": {" + sb.ToString() + "},\"TagKey\":\"" + tttttkey + "\"}";
        public static void ReSetSuppliers(List<string> list, int SupplierType, string key)
        {


            //删除数据库中的不在白名单的供应商
            var whiteSupplier = list.ToArray();
            //DelSupplierByName(SupplierType, key, whiteSupplier);
            //添加默认的供应商
            //AddDefaultSupplier(SupplierType, key);
            //打开开关 
            string productName = GoodsType.GetGoodsName(SupplierType);
            HashParam hparam = new HashParam();
            if (list.Count == 0)
                list.Add(key);
            hparam.Add(productName, list);
            var strList = JsonConvert.SerializeObject(hparam);
            #region 格式化白名单 设置白名单接口
            var setSupplierJson = "{\"whitelist\":" + strList + "}";
            string guid = Guid.NewGuid().ToString();
            var objParams = JsonConvert.DeserializeObject<JObject>(setSupplierJson);
            var lastStr = MyHttpRequest.NestedDictSort2Str(objParams);
            int totalSeconds;
            string signStr;
            MyHttpRequest.SignByParams(guid, lastStr.ToString(), key, out totalSeconds, out signStr);
            RequestInfo rif = new RequestInfo() { RequestJson = setSupplierJson, RequestUrl = string.Format(GlobalConfig.TransmissionSuppliersSetUrl) };
            //需要显示的供应商
            var responseJson = MyHttpRequest.PostJSONByRequestParam(rif, 3, guid, signStr, totalSeconds, null, Yunzuan.Foundation.Web_api.MyHttpRequest.RequestLib.PUT);
            //打开开关
            OpenSupplierDelegate openSupplier = OpenSupplier;
            foreach (string item in list)
            {
                HashParam hs = new HashParam();
                hs.Add("category", productName);
                hs.Add("state", true);
                hs.Add("SupplierCode", item);
                openSupplier.Invoke(hs, key);
            }

            #endregion
        }
        /// <summary>
        /// 添加默认的供应商
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static void AddDefaultSupplier(int SupplierType, string key)
        {
            HashParam setParam = new HashParam();
            setParam.Add("SupplierCode", key);
            setParam.Add("SupplierType", SupplierType);
            SupplierInfo supplier = YZ.GetDatabase(key).QueryForObject<SupplierInfo>("Supplier.RegIsExist", setParam);
            if (supplier == null&&setParam.ContainsKey("SupplierCode"))
            {
                var code = setParam.GetString("SupplierCode");
                supplier = new SupplierInfo()
                {
                    SupplierCode = code,
                    SupplierName = code,
                    SupplierShortName = code,
                    SupplierType = setParam.GetInt("SupplierType")
                };
                var a = YZ.GetDatabase(key).Add(supplier);
            }
        }

        /// <summary>
        /// 删除数据库中的不在白名单的供应商
        /// </summary>
        /// <param name="SupplierType"></param>
        /// <param name="key"></param>
        /// <param name="supplierList"></param>
        public static void DelSupplierByName(int SupplierType, string key, string[] supplierList)
        {
            try
            {
                Hashtable hparam = new Hashtable();
                hparam.Add("SupplierType", SupplierType);
                if (supplierList.Length > 0)
                    hparam.Add("SupplierNames", supplierList);
                var i = YZ.GetDatabase(key).Delete("Supplier.DelSupplierName", hparam);
            }
            catch (Exception)
            {

                throw;
            }

        }
        public delegate void OpenSupplierDelegate(HashParam strParam, string key);

        /// <summary>
        /// 打开开关
        /// </summary>
        /// <param name="strParam"></param>
        /// <param name="tttagKey"></param>
        public static void OpenSupplier(HashParam strParam, string tttagKey)
        {
            try
            {
                Dictionary<string, bool> dicts = new Dictionary<string, bool>(); //组装成新的数据中心的格式
                dicts.Add(strParam.GetString("category"), strParam.GetBool("state"));
                string guid = Guid.NewGuid().ToString();
                var objParams = JsonConvert.DeserializeObject<JObject>(JsonConvert.SerializeObject(dicts));
                var lastStr = MyHttpRequest.NestedDictSort2Str(objParams);
                int totalSeconds;
                string signStr;
                MyHttpRequest.SignByParams(guid, lastStr.ToString(), tttagKey, out totalSeconds, out signStr);
                RequestInfo rif = new RequestInfo() { RequestJson = JsonConvert.SerializeObject(dicts), RequestUrl = string.Format(GlobalConfig.TransmissionSupplierWhiteSetUrl, strParam.GetString("SupplierCode")) };
                var responseJson = MyHttpRequest.PostJSONByRequestParam(rif, 3, guid, signStr, totalSeconds, null, Yunzuan.Foundation.Web_api.MyHttpRequest.RequestLib.PUT);
            }
            catch (Exception)
            {

                throw;
            }
        }
        #endregion

        #region  黑名单
        public static string AddBlackList(string strParam)
        {
            HashParam hp = JsonConvert.DeserializeObject<HashParam>(strParam);
            if (hp.ContainsKey("type") && hp.GetString("type") != "")
            {
                if (hp.GetString("type").ToLower() == "mobile")
                {
                    string[] list = HttpContext.Current.Cache.Get("Cache:BlackMobiles") as string[];
                    if (!list.Contains(hp.GetString("value")))
                    {
                        List<string> b = list.ToList();
                        b.Add(hp.GetString("value"));
                        list = b.ToArray();
                        HttpContext.Current.Cache.Insert("Cache:BlackMobiles", list, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromDays(1));
                    }
                }
                if (hp.GetString("type").ToLower() == "ip")
                {
                    string[] list = HttpContext.Current.Cache.Get("Cache:IPs") as string[];
                    if (!list.Contains(hp.GetString("value")))
                    {
                        List<string> b = list.ToList();
                        b.Add(hp.GetString("value"));
                        list = b.ToArray();
                        HttpContext.Current.Cache.Insert("Cache:IPs", list, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromDays(1));
                    }
                }
            }
            MessageServiceClient mc = new MessageServiceClient();
            return mc.AddBlackList(strParam);
        }
        public static string DelBlackList(string strParam)
        {
            HashParam hp = JsonConvert.DeserializeObject<HashParam>(strParam);
            if (hp.ContainsKey("type") && hp.GetString("type") != "")
            {
                if (hp.GetString("type").ToLower() == "mobile")
                {
                    string[] list = HttpContext.Current.Cache.Get("Cache:BlackMobiles") != null ? HttpContext.Current.Cache.Get("Cache:BlackMobiles") as string[] : new string[] { };
                    if (list.Contains(hp.GetString("value")))
                    {
                        List<string> b = list.ToList();
                        b.Remove(hp.GetString("value"));
                        list = b.ToArray();
                        HttpContext.Current.Cache.Insert("Cache:BlackMobiles", list, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromDays(1));
                    }
                }
                if (hp.GetString("type").ToLower() == "ip")
                {
                    string[] list = HttpContext.Current.Cache.Get("Cache:BlackIPs") != null ? HttpContext.Current.Cache.Get("Cache:BlackIPs") as string[] : new string[] { };
                    if (list.Contains(hp.GetString("value")))
                    {
                        List<string> b = list.ToList();
                        b.Remove(hp.GetString("value"));
                        list = b.ToArray();
                        HttpContext.Current.Cache.Insert("Cache:BlackIPs", list, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromDays(1));
                    }
                }
            }
            MessageServiceClient mc = new MessageServiceClient();
            return mc.DelBlackList(strParam);
        }
        public static string SearchBlackList()
        {
            MessageServiceClient mc = new MessageServiceClient();
            var result = mc.SearchBlackList();
            if (HttpContext.Current.Cache.Get("Cache:BlackMobiles") == null || HttpContext.Current.Cache.Get("Cache:IPs") == null)
            {
                var list = JsonConvert.DeserializeObject<List<Blacklist>>(result);
                if (list.Count > 0)
                {
                    //1 mobile,2 IP
                    var listMobile = from i in list
                                     where i.BlackType == 1
                                     select i.BlackValue;
                    if (listMobile.Count() > 0)
                    {
                        HttpContext.Current.Cache.Insert("Cache:BlackMobiles", listMobile.ToArray(), null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromDays(1));
                    }
                    else
                    {
                        HttpContext.Current.Cache.Insert("Cache:BlackMobiles", new string[] { }, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromDays(1));
                    }

                    var listIp = from i in list
                                 where i.BlackType == 2
                                 select i.BlackValue;
                    if (listIp.Count() > 0)
                    {
                        HttpContext.Current.Cache.Insert("Cache:BlackIPs", listIp.ToArray(), null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromDays(1));
                    }
                    else
                    {
                        HttpContext.Current.Cache.Insert("Cache:BlackIPs", new string[] { }, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromDays(1));
                    }
                }
            }
            return result;
        }
        #endregion
    }

    public class Blacklist
    {
        public int ID { get; set; }
        public int BlackType { get; set; }
        public string BlackValue { get; set; }
        public DateTime CreateDate { get; set; }
    }
}